

using System;
using System.Data;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Diagnostics.CodeAnalysis;
using System.Linq;

namespace UserBook.Repository
{
	[ExcludeFromCodeCoverage]
    public partial class EntityRepository<E> : IRepository<E> where E : EntityObject
    {
        protected readonly ObjectContext context;
        protected readonly ObjectSet<E> objectSet;

        public EntityRepository(ObjectContext context)
        {
            #region Argument Validation

            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            #endregion

            this.context = context;
            this.objectSet = context.CreateObjectSet<E>();
        }

        public virtual IQueryable<E> All()
        {
            return objectSet;
        }

        public virtual IQueryable<E> All(string includes)
        {
            ObjectQuery<E> value = objectSet;
            if (String.IsNullOrEmpty(includes))
            {
                foreach (var includeProperty in includes.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    value = value.Include(includeProperty.Trim());
                }
            }
            return value;
        }

        public virtual void Add(E entity)
        {
            #region Argument Validation

            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            #endregion

            objectSet.AddObject(entity);
        }

        public virtual void Remove(E entity)
        {
            #region Argument Validation

            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            #endregion

            if (entity.EntityState == EntityState.Detached)
            {
                objectSet.Attach(entity);
            }

            objectSet.DeleteObject(entity);
        }

        public virtual void Save()
        {
            context.SaveChanges();
        }
    }
}

